package com.qf.springboot.controller;

import com.qf.springboot.async.LikeSleep;
import com.qf.springboot.dto.AirDTO;
import com.qf.springboot.entity.Air;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.annotations.ApiIgnore;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.Date;

/**
 * @author zjw
 */
@RestController
@Api(tags = "用于SpringBoot测试的Controller")
public class TestController {

    @Value("${project-version:v0.0.0}")
    private String version;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/test")
    @ApiOperation(value = "专门用于测试的小方法")
    public String test(@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday){
        return "Create My Maven Spring Boot!" + version;
    }

    @PostMapping("/air/add")
    public AirDTO add(@RequestBody @Valid AirDTO airDTO, @ApiIgnore BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            // 有参数不满足注解要求
            String msg = bindingResult.getFieldError().getDefaultMessage();
            System.out.println(msg);
            return null;
        }
        System.out.println(airDTO);
        return airDTO;
    }

    @Autowired
    private LikeSleep likeSleep;

    @GetMapping("/rest")
    public String rest() throws MessagingException {
        // POST   ,  http://192.168.41.98/user/signin
        // body ->  {"username": "xxx", "password": "xxx"}
        // 传递JSON参数时，需要请求头和请求体
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String body = "{\"username\": \"xxx\", \"password\": \"xxx\"}";
        HttpEntity httpEntity = new HttpEntity(body,httpHeaders);
        String result = restTemplate.postForObject("http://192.168.41.98/user/signin", httpEntity, String.class);
        System.out.println(result);

        System.out.println(Thread.currentThread().getName());
        likeSleep.sleep();
        return result;
    }

}
